<template>
  <div class="reservation-container">
    <div class="header-card">
      <h2 class="header-title">我的预订</h2>
      <div class="payment-alert" v-if="pendingPaymentCount > 0">
        <el-alert
          title="待支付提醒"
          type="warning"
          :description="`您有 ${pendingPaymentCount} 个订单待支付，请及时完成支付以免订单过期！`"
          show-icon
          :closable="false"
          class="payment-reminder"
        />
      </div>
      <div class="header-content">
        <p class="header-description">以下是您的所有会议室预订记录</p>
        <select v-model="selectedStatus" class="status-select">
          <option value="all">全部状态</option>
          <option value="PENDING_PAYMENT">待支付</option>
          <option value="CONFIRMED">已确认</option>
          <option value="IN_USE">使用中</option>
          <option value="COMPLETED">已完成</option>
          <option value="CANCELLATION_REQUESTED">取消申请中</option>
          <option value="CANCELLED">已取消</option>
          <option value="PAYMENT_EXPIRED">逾期未支付</option>
        </select>
      </div>
    </div>

    <div class="reservation-list-container">
      <div class="reservation-grid">
        <div
          v-for="reservation in filteredReservations"
          :key="reservation.id"
          class="reservation-card"
        >
          <div class="card-content">
            <div class="card-header">
              <h3 class="room-name">
                {{ getRoomName(reservation.roomId) }}
              </h3>
              <span class="status-badge" :class="'status-' + reservation.status.toLowerCase()">
                {{ formatStatus(reservation.status) }}
              </span>
            </div>

            <div class="card-details">
              <div class="detail-item">
                <p>
                  <span class="detail-label">预订时间：</span>
                  {{ formatDate(reservation.startTime) }}
                  {{ formatTime(reservation.startTime) }} -
                  {{ formatTime(reservation.endTime) }}
                </p>
                <p><span class="detail-label">参与人数：</span>{{ reservation.participants }}人</p>
                <p>
                  <span class="detail-label">设备需求：</span
                  >{{ reservation.equipmentRequiredNotes || '无' }}
                </p>
                <p>
                  <span class="detail-label">总价：</span>¥{{ reservation.totalPrice.toFixed(2) }}
                </p>
              </div>
            </div>
          </div>

          <div class="card-footer">
            <div class="payment-warning" v-if="reservation.status === 'PENDING_PAYMENT'">
              <p class="warning-text">
                请在
                {{ formatDateTime(calculatePaymentExpireTime(reservation.orderGeneratedAt)) }}
                前完成支付
              </p>
            </div>
            <div class="action-buttons">
              <button
                v-if="reservation.status === 'PENDING_PAYMENT'"
                @click="handlePayment(reservation)"
                class="payment-button"
              >
                立即支付
              </button>
              <button
                v-if="reservation.status === 'CONFIRMED'"
                @click="showCancelConfirm(reservation)"
                class="cancel-button"
              >
                申请取消
              </button>
            </div>
          </div>
        </div>

        <div v-if="filteredReservations.length === 0" class="no-reservation">
          <p>没有找到符合条件的预订。</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted, watch } from 'vue'
import axios from 'axios'
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useReservationStore } from '@/stores/reservation'

const router = useRouter()
const customerReservations = ref([])
const selectedStatus = ref('all')
const timer = ref(null)
const reservationStore = useReservationStore()

// 修改监听部分
watch(
  () => reservationStore.needRefresh,
  async (newValue) => {
    if (newValue) {
      await fetchReservations()
      reservationStore.setNeedRefresh(false)
    }
  },
  { immediate: true } // 添加 immediate: true，确保组件挂载时就执行一次
)

// 修改 fetchReservations 方法
const fetchReservations = async () => {
  const authStore = useAuthStore()
  const userId = authStore.user?.userId

  if (!userId) return

  try {
    const response = await axios.get(`http://localhost:8080/api/reservations/user/${userId}`)
    customerReservations.value = response.data.filter((r) => r.status !== 'Scheduled')
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取预订信息时发生错误。')
  }
}

// 修改 onMounted
onMounted(async () => {
  const authStore = useAuthStore()

  const isAuthenticated = await authStore.checkAuth()
  if (!isAuthenticated) {
    ElMessage.error('用户未认证。请登录。')
    router.push('/login')
    return
  }

  const userId = authStore.user?.userId
  if (!userId) {
    ElMessage.error('用户信息获取失败，请重新登录。')
    router.push('/login')
    return
  }

  // 每秒更新一次倒计时
  timer.value = setInterval(() => {
    customerReservations.value = [...customerReservations.value]
  }, 1000)

  // 设置需要刷新标志
  reservationStore.setNeedRefresh(true)
})

onUnmounted(() => {
  // 组件销毁时清除定时器
  if (timer.value) {
    clearInterval(timer.value)
  }
})

const filteredReservations = computed(() => {
  if (selectedStatus.value === 'all') {
    return customerReservations.value
  }

  return customerReservations.value.filter((r) => {
    return r.status === selectedStatus.value
  })
})

// 修改 getRoomName 函数直接返回 roomName
const getRoomName = (roomId) => {
  const reservation = customerReservations.value.find((r) => r.roomId === roomId)
  return reservation?.roomName || '会议室'
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return `${date.getMonth() + 1}月${date.getDate()}日`
}

const formatTime = (dateString) => {
  const date = new Date(dateString)
  return `${date.getHours().toString().padStart(2, '0')}:${date
    .getMinutes()
    .toString()
    .padStart(2, '0')}`
}

const formatDateTime = (dateString) => {
  const date = new Date(dateString)
  return `${date.getFullYear()}年${
    date.getMonth() + 1
  }月${date.getDate()}日 ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}:${date
    .getSeconds()
    .toString()
    .padStart(2, '0')}`
}

const calculateRefundAmount = (reservation) => {
  const now = new Date()
  const startTime = new Date(reservation.startTime)
  const hoursDiff = (startTime - now) / (1000 * 60 * 60)

  if (hoursDiff > 72) return reservation.totalPrice
  if (hoursDiff > 48) return reservation.totalPrice * 0.75
  if (hoursDiff > 24) return reservation.totalPrice * 0.25
  return 0
}

const formatStatus = (status) => {
  const statusMap = {
    CONFIRMED: '已确认',
    PENDING_PAYMENT: '待支付',
    IN_USE: '使用中',
    COMPLETED: '已完成',
    CANCELLATION_REQUESTED: '取消申请中',
    CANCELLED: '已取消',
    PAYMENT_EXPIRED: '逾期未支付',
  }
  return statusMap[status] || status
}

const handlePayment = async (reservation) => {
  try {
    await ElMessageBox.confirm(
      `<div class="payment-confirm-content">
        <div class="confirm-title">确认支付 ${getRoomName(reservation.roomId)} 的预订吗？</div>
        <div class="confirm-detail">
          <div><span class="detail-label">开始时间：</span>${formatDateTime(
            reservation.startTime
          )}</div>
          <div class="payment-amount"><span class="detail-label">支付金额：</span>¥${reservation.totalPrice.toFixed(
            2
          )}</div>
        </div>
      </div>`,
      '确认支付',
      {
        confirmButtonText: '立即支付',
        cancelButtonText: '再等等',
        type: 'warning',
        dangerouslyUseHTMLString: true,
        customClass: 'payment-confirm-dialog',
        width: '500px',
      }
    )

    // 用户确认支付后执行支付逻辑
    const response = await axios.put(
      `http://localhost:8080/api/reservations/confirm-reservation/${reservation.bookingId}`
    )
    if (response.data) {
      ElMessage.success('支付成功！')
      const index = customerReservations.value.findIndex(
        (r) => r.bookingId === reservation.bookingId
      )
      if (index !== -1) {
        // 使用Vue响应式方式更新状态
        customerReservations.value = [
          ...customerReservations.value.slice(0, index),
          { ...customerReservations.value[index], status: 'CONFIRMED' },
          ...customerReservations.value.slice(index + 1),
        ]
      }
    }
  } catch (error) {
    // 用户点击了取消或支付失败
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '支付过程中发生错误')
    }
  }
}

const showCancelConfirm = async (reservation) => {
  const refund = calculateRefundAmount(reservation)
  try {
    await ElMessageBox.confirm(
      `<div class="cancel-confirm-content">
        <div class="confirm-title">确定要取消 ${getRoomName(reservation.roomId)} 的预订吗？</div>
        <div class="confirm-detail">
          <div><span class="detail-label">开始时间：</span>${formatDateTime(
            reservation.startTime
          )}</div>
          <div class="refund-amount"><span class="detail-label">可退款金额：</span>¥${refund.toFixed(
            2
          )}</div>
        </div>
        <div class="cancel-policy">
          <div class="policy-title">取消规则：</div>
          <div>72小时前：全额退款</div>
          <div>48-72小时：退款75%</div>
          <div>24-48小时：退款25%</div>
          <div>24小时内：不予退款</div>
        </div>
      </div>`,
      '确认取消预订',
      {
        confirmButtonText: '确认取消',
        cancelButtonText: '再想想',
        type: 'warning',
        dangerouslyUseHTMLString: true,
        customClass: 'cancel-confirm-dialog',
        width: '500px',
      }
    )
    await requestCancellation(reservation)
  } catch (error) {
    // 用户点击了取消
  }
}

const requestCancellation = async (reservation) => {
  try {
    const response = await axios.put(
      `http://localhost:8080/api/reservations/cancel-request/${reservation.bookingId}`
    )
    if (response.data) {
      ElMessage.success('取消请求已成功提交！')
      const index = customerReservations.value.findIndex(
        (r) => r.bookingId === reservation.bookingId
      )
      if (index !== -1) {
        // 使用响应式更新方式
        customerReservations.value = [
          ...customerReservations.value.slice(0, index),
          { ...customerReservations.value[index], status: 'CANCELLATION_REQUESTED' },
          ...customerReservations.value.slice(index + 1),
        ]
      }
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '提交取消请求时发生错误。')
  }
}

const calculatePaymentExpireTime = (orderGeneratedAt) => {
  const expireTime = new Date(orderGeneratedAt)
  expireTime.setMinutes(expireTime.getMinutes() + 30)
  return expireTime
}

const calculateRemainingTime = (orderGeneratedAt) => {
  const now = new Date()
  const expireTime = new Date(orderGeneratedAt)
  expireTime.setMinutes(expireTime.getMinutes() + 30)

  const timeDiff = expireTime - now
  if (timeDiff <= 0) return '已超时'

  const minutes = Math.floor(timeDiff / (1000 * 60))
  const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000)

  return `${minutes}分${seconds}秒`
}

const pendingPaymentCount = computed(() => {
  return customerReservations.value.filter((r) => r.status === 'PENDING_PAYMENT').length
})
</script>

<style>
/* 全局弹窗样式 */
.payment-confirm-dialog .el-message-box__content {
  padding: 20px;
  font-size: 14px;
  line-height: 1.5;
}
.payment-confirm-content {
  color: #606266;
}
.confirm-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
}
.confirm-detail {
  margin: 15px 0;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}
.detail-label {
  font-weight: 600;
  color: #606266;
  min-width: 80px;
  display: inline-block;
}
.payment-amount {
  margin-top: 8px;
  color: #67c23a;
  font-weight: bold;
}

.cancel-confirm-dialog .el-message-box__content {
  padding: 20px;
  font-size: 14px;
  line-height: 1.5;
}
.cancel-confirm-content {
  color: #606266;
}
.confirm-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
}
.confirm-detail {
  margin: 15px 0;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}
.detail-label {
  font-weight: 600;
  color: #606266;
  min-width: 80px;
  display: inline-block;
}
.refund-amount {
  margin-top: 8px;
  color: #e6a23c;
  font-weight: bold;
}
.cancel-policy {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #ebeef5;
}
.policy-title {
  font-weight: 600;
  margin-bottom: 8px;
}
.cancel-confirm-dialog .el-message-box__btns {
  padding-top: 15px;
}
</style>

<style scoped>
/* 样式部分保持不变 */
.reservation-container {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.header-card {
  background: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border-radius: 0.5rem;
  padding: 1.5rem;
}

.header-title {
  font-size: 1.125rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 1rem;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-description {
  color: #4b5563;
}

.status-select {
  display: block;
  padding: 0.5rem 2.5rem 0.5rem 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 0.375rem;
  outline: none;
}

.reservation-list-container {
  background-color: #e3f2fd;
  padding: 1.5rem;
  border-radius: 0.75rem;
}

.reservation-grid {
  display: grid;
  grid-template-columns: repeat(1, 1fr);
  gap: 2rem;
}

@media (min-width: 768px) {
  .reservation-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (min-width: 1024px) {
  .reservation-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

.reservation-card {
  background: white;
  border-radius: 0.75rem;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  border: 1px solid #f3f4f6;
  transition: all 0.3s ease;
}

.reservation-card:hover {
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  transform: translateY(-0.25rem);
}

.card-content {
  padding: 1.25rem;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 0.75rem;
}

.room-name {
  font-size: 1.125rem;
  font-weight: 700;
  color: #1f2937;
}

.status-badge {
  padding: 0.25rem 0.75rem;
  border-radius: 9999px;
  font-size: 0.75rem;
  font-weight: 600;
}

.card-details {
  border-top: 1px solid #f3f4f6;
  padding-top: 0.75rem;
  margin-top: 0.75rem;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  font-size: 0.875rem;
  color: #374151;
}

.detail-label {
  font-weight: 500;
}

.card-footer {
  padding: 1rem 1.25rem;
  border-top: 1px solid #f3f4f6;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f9fafb;
}

.payment-warning {
  flex: 1;
  padding-right: 1rem;
}

.warning-text {
  color: #dc2626;
  font-size: 0.875rem;
  font-weight: 500;
}

.cancel-policy {
  font-size: 0.75rem;
  color: #6b7280;
}

.action-buttons {
  display: flex;
  gap: 0.5rem;
}

.payment-button {
  padding: 0.375rem 1rem;
  background: #2563eb;
  color: white;
  font-size: 0.875rem;
  border-radius: 0.375rem;
  transition: background-color 0.2s;
}

.payment-button:hover {
  background: #1d4ed8;
}

.cancel-button {
  padding: 0.375rem 1rem;
  background: #dc2626;
  color: white;
  font-size: 0.875rem;
  border-radius: 0.375rem;
  transition: background-color 0.2s;
}

.cancel-button:hover {
  background: #b91c1c;
}

.no-reservation {
  grid-column: 1 / -1;
  text-align: center;
  color: #6b7280;
  padding: 2rem 0;
}

.status-badge {
  padding: 0.25rem 0.75rem;
  border-radius: 9999px;
  font-size: 0.75rem;
  font-weight: 600;
  display: inline-block;
}

.status-pendingpayment,
.status-pending_payment {
  background-color: #fef3c7;
  color: #92400e;
}

.status-confirmed {
  background-color: #d1fae5;
  color: #065f46;
}

.status-in_use {
  background-color: #dbeafe;
  color: #1e40af;
}

.status-completed {
  background-color: #f3f4f6;
  color: #374151;
}

.status-cancellation_requested {
  background-color: #ffedd5;
  color: #9a3412;
}

.status-cancelled {
  background-color: #fee2e2;
  color: #991b1b;
}

.status-payment_expired {
  background-color: #f5f5f5;
  color: #5c5959;
}

.payment-alert {
  margin: 1rem 0;
}

.payment-reminder {
  border-radius: 8px;
}

:deep(.payment-reminder .el-alert__title) {
  font-size: 1rem;
  font-weight: 600;
}

:deep(.payment-reminder .el-alert__description) {
  font-size: 0.9rem;
  margin: 0.5rem 0;
  color: #955005;
}

:deep(.payment-reminder .el-alert__icon) {
  font-size: 1.2rem;
  color: #d97706;
}
</style>
